package com.study.samsung.Control;

import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.study.samsung.Entity.Commodity;
import com.study.samsung.Entity.Succession;
import com.study.samsung.Entity.User;
import com.study.samsung.Service.GoodsService;
import com.study.samsung.Service.IndexSearchService;
import com.study.samsung.Service.UserService;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpRetryException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//个人信息
@WebServlet("/PersonalInformation")
@MultipartConfig
public class PersonalInformationServlet extends HttpServlet {
    UserService service = new UserService();
    IndexSearchService iss = new IndexSearchService();
    GoodsService gds = new GoodsService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //是否已经登录。如果没有登录，直接跳登录
        HttpSession session = req.getSession();
        Object obj = session.getAttribute("user");
        if (obj==null){
            resp.sendRedirect("/login");
        }else {

            List<Commodity> newgoods = iss.selectnew();
            List<Succession> selectxl = iss.selectxl();

            req.setAttribute("newgoods",newgoods);
            req.setAttribute("selectxl",selectxl);

            Object user = session.getAttribute("user");
            if (user!=null){
                User nowuser = (User) user;
                Integer uid = nowuser.getUid();

                session.setAttribute("cartcount",gds.cartcount(uid));
            }
            req.getRequestDispatcher("/WEB-INF/jsp/PersonalInformation.jsp")
                    .forward(req,resp);
        }
    }

        @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(13);
        req.setCharacterEncoding("utf-8");

        JSONObject  json = new JSONObject();
        HttpSession session = req.getSession();
        String username = req.getParameter("nickname");
        String sex = req.getParameter("sex");

        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
        String birth = req.getParameter("birth");


        Date date = time.parse(birth);


        Part part = req.getPart("myfile");

        String path = req.getServletContext().getRealPath("/");
        String upPath = path+"img/"+username+"/";

        File file = new File(upPath);

        if (!file.exists()){
            file.mkdirs();
        }

//获取原始文件名
        String oldName = part.getSubmittedFileName();
        String newName = uniqeName()+getSuffix(oldName);

            part.write(upPath+newName);


        Object obj = session.getAttribute("user");



        if (obj==null){
            json.put("code",-1);
        }else {
            User u = new User();
            User sessionUser = (User)obj;
            sessionUser.setNickname(username);
            sessionUser.setSex(sex);
            sessionUser.setBirth(date);
            System.out.println(username);
            sessionUser.setUpicture("/img/"+username+"/"+newName);
            System.out.println("uuuu="+u);
//            去数据库更新
            service.doUpdate(sessionUser);

            json.put("code",1);
            json.put("uname",sessionUser.getUname());
            json.put("src","/img/"+username+"/"+newName);
        }

        PrintWriter out = resp.getWriter();
        out.println(json.toJSONString());
        out.close();
    }
    public String getSuffix(String oldName){
        int i = oldName.lastIndexOf(".");
        System.out.println("i="+i);
        return oldName.substring(i);
    }

    public String uniqeName(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = sdf.format(date);
//        生成四位数的随机数 1-9999之间，不够四位的，补齐四位，0001
        int rnd = (int)(Math.random()*9999)+1;
        String n = rnd+"";
        for (int i=0;i<(4-n.length());i++){
            n="0"+n;
        }
        return s+n;
    }
}
